/* Assumes that the queue has already been initialized */

#include "includes.h"
#include "queue.h"
#include <stdio.h>

const int IOTIME = 10; /* in mS */
static struct queue q;
static int io_time_remaining = -1;

void io_advance_clock(int advance)
{
  io_time_remaining = io_time_remaining - advance;	
}

void io_add_to_queue(struct proc_info *proc)
{
  /*If the queue is empty reset timer for i/o completion
    else just add to the end of the queue*/
  if(queue_empty_p(&q))
    {
      /*Add new process to I/O Queue*/
      enqueue(&q, proc);
      io_time_remaining = IOTIME;	
    }
  else
    {
      enqueue(&q,proc);
    }
  return;
	
}

struct proc_info* io_get_next()
{
  struct proc_info *proc;
  proc = dequeue(&q);

  /*Decrement number of I/Os remaining*/
  proc->ios_remaining = proc->ios_remaining-1;
  
  /* Reset process io counter */
  proc->time_to_next_io = proc->io_interval;


  /*Completed last I/0 so starting next I/0*/
  io_time_remaining = IOTIME;

  return proc;
}

long io_next_event_time()
{
  if (queue_empty_p(&q))
    {
      return -1;
    }
  else
    {
      return clock_time + io_time_remaining;
    }
}

void io_init() {
  init_queue(&q);
}
